import json
from flask import request
from conf.db import get_db
from core.crontab import Crontab
from core.schedule import SSH, TasksSchedule

TaskPool = {}
runStartTasks = False


class SshController:
    def __init__(self):
        self.db = get_db()
        # 启动已开启的任务
        global runStartTasks
        if runStartTasks is False:
            print('启动已开启的任务')
            all_tasks = self.db.findAll('tasks', 'status = 1')
            for task in all_tasks:
                ecs = self.db.find('esc_resource', 'id = {}'.format(task['ecs_id']))
                self._run_task(ecs, task, task['id'])
            runStartTasks = True

    def _run_task(self, ecs, task, _id):
        ecs['host'] = ecs['ip_address']
        ecs['username'] = ecs['account']
        ts = TasksSchedule(task, ecs)
        cron = Crontab(task['crontab_expression'], ts.work)
        cron.run()
        TaskPool[str(_id)] = cron  # 加入任务池，方便停止任务
        self.db.update('tasks', {'status': 1}, 'id = {}'.format(_id))  # 更新为启动任务

    def start_task(self):
        _id = request.args.get('id', 0)
        task = self.db.find('tasks', 'id = {}'.format(_id))
        ecs = self.db.find('esc_resource', 'id = {}'.format(task['ecs_id']))
        self._run_task(ecs, task, _id)
        return json.dumps({'error': 0, 'message': '启动任务成功'})

    def stop_task(self):
        _id = request.args.get('id', 0)
        task = self.db.find('tasks', 'id = {}'.format(_id))
        if not task:
            return json.dumps({'error': 1, 'message': '停止失败，任务不存在！'})
        TaskPool[str(_id)].stop()
        self.db.update('tasks', {'status': 2}, 'id = {}'.format(_id))  # 更新为停止任务
        return json.dumps({'error': 0, 'message': '停止任务成功'})

    def connect_test(self):
        _id = request.args.get('id', 0)
        ecs = self.db.find('esc_resource', 'id = {}'.format(_id))
        ecs['host'] = ecs['ip_address']
        ecs['username'] = ecs['account']
        try:
            SSH(ecs)
            return json.dumps({'error': 0, 'message': '连接成功', 'all_tasks': len(TaskPool)})
        except Exception as e:
            return json.dumps({'error': 1, 'message': '{}'.format(e)})

    # 测试任务执行情况
    def test_task(self):
        _id = request.args.get('id', 0)
        task = self.db.find('tasks', 'id = {}'.format(_id))
        ecs = self.db.find('esc_resource', 'id = {}'.format(task['ecs_id']))
        ecs['host'] = ecs['ip_address']
        ecs['username'] = ecs['account']
        try:
            ts = TasksSchedule(task, ecs)
            rst = ts.work()
            return json.dumps({'error': 0, 'message': '成功', 'result': rst})
        except Exception as e:
            return json.dumps({'error': 1, 'message': '{}'.format(e)})
